package ro.fortech.peaa.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ro.fortech.peaa.domain.Job;
import ro.fortech.peaa.repository.api.IJobMapper;
import ro.fortech.peaa.service.api.IJobIdentityMap;
import ro.fortech.peaa.service.api.IJobManager;

public class JobManagerWithIdentityMap extends JobManager implements IJobManager {
	private IJobMapper jobMapper;
	private IJobIdentityMap jobIdentityMap;
	protected Log logger = LogFactory.getLog(getClass());

	public void setJobIdentityMap(IJobIdentityMap jobIdentityMap) {
		this.jobIdentityMap = jobIdentityMap;
	}
	public void setJobMapper(IJobMapper jobMapper) {
		this.jobMapper = jobMapper;
	}
	
	/*
	 * (non-Javadoc)
	 * @see ro.fortech.peaa.service.api.IJobManager#deleteJob(ro.fortech.peaa.domain.Job)
	 */
	@Override
	public void deleteJob(Job job) throws Exception {
		jobMapper.delete(job);
		jobIdentityMap.remove(job);
	}

	/*
	 * (non-Javadoc)
	 * @see ro.fortech.peaa.service.api.IJobManager#find(java.lang.String)
	 */
	@Override
	public Job find(String id) throws Exception {
		// check first if job on identity map (if exist) is a complete version
		Job job = jobIdentityMap.get(id); 
		if (job != null && job.getMaxSalary() != null) {
			return job;
		}
		// job was incomplete or inexistent on the identity map
		return jobMapper.find(id);
	}

	/*
	 * (non-Javadoc)
	 * @see ro.fortech.peaa.service.api.IJobManager#findAll()
	 */
	@Override
	public List<Job> findAll() throws Exception {
		List<Job> jobs = new ArrayList<Job>(jobIdentityMap.getAll());
		if (jobs.size() == 0) {
			jobs = jobMapper.findAll();
			for (Job job : jobs) {
				jobIdentityMap.put(job);
			}
		} else {
			// If there are jobs that have null maxSalary then get them from db
			int i = 0;
			for (; i < jobs.size(); i++)  {
				Job job = jobs.get(i);
				if (job.getMaxSalary() == null) {
					job = jobMapper.find(job.getId());
					jobs.set(i, job);
					jobIdentityMap.put(job);
				}
			}
		}
		return jobs;
	}
	
	/*
	 * (non-Javadoc)
	 * @see ro.fortech.peaa.service.api.IJobManager#findAllIdAndTitle()
	 */
	@Override
	public List<Job> findAllIdAndTitle() throws Exception {
		List<Job> jobs = jobIdentityMap.getAll();
		if (jobs.size() < 1) {
			jobs = jobMapper.findAll();
			for(Job job : jobs) {
				jobIdentityMap.put(job);
			}
		}
		return jobs;
	}

	/*
	 * (non-Javadoc)
	 * @see ro.fortech.peaa.service.api.IJobManager#insertJob(ro.fortech.peaa.domain.Job)
	 */
	@Override
	public void insertJob(Job job) throws Exception {
		jobMapper.insert(job);
		jobIdentityMap.put(job);
	}

	/*
	 * (non-Javadoc)
	 * @see ro.fortech.peaa.service.api.IJobManager#updateJob(ro.fortech.peaa.domain.Job)
	 */
	@Override
	public void updateJob(Job job) throws Exception {
		jobMapper.update(job);
		jobIdentityMap.put(job);
	}

}
